﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Configuration;
using System.Web.Hosting;

namespace LibMS.Controllers
{
    [Authorize]
    public class ApiFileActionController : ApiController
    {
        private string _localFilePath = ConfigurationManager.AppSettings["BaseDataFolder"];

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetFile(string fileName)
        {
            HttpResponseMessage result = null;
            var localFilePath = HostingEnvironment.MapPath(_localFilePath + fileName);

            // check if parameter is valid
            if (String.IsNullOrEmpty(fileName))
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            // check if file exists on the server
            else if (!File.Exists(localFilePath))
            {
                result = Request.CreateResponse(HttpStatusCode.Gone);
            }
            else
            {// serve the file to the client
            result = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
            result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition.FileName = fileName;
            }

            return result;
        }
    }
}
